import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Modal, Input } from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import axios from 'axios'
import Form from 'antd/es/form/Form'
const { confirm } = Modal
export default function NewsCategory() {
  const [DataList, setDataList] = useState()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const addModal = useRef()

  useEffect(() => {
    getDataList()
  }, [])

  const getDataList = () => {
    axios.get('/categories').then((res) => {
      setDataList(res.data)
    })
  }

  //删除
  const deleteData = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(item)
      },
      onCancel() {},
    })
  }
  const deleteMethod = async (item) => {
    await axios.delete(`/categories/${item.id}`)
    getDataList()
  }
  const addtitle = async () => {
    const value = await addModal.current.validateFields()
    await axios.post(`/categories`, { title: value.title, value: value.title })
    setIsModalOpen(false)
    getDataList()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      },
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
    },
    {
      title: '操作',
      key: 'operate',
      render: (item) => {
        return (
          <Button
            danger
            icon={<DeleteOutlined></DeleteOutlined>}
            onClick={() => deleteData(item)}
          ></Button>
        )
      },
    },
  ]
  return (
    <div>
      <Button type="primary" onClick={() => setIsModalOpen(true)}>
        +添加
      </Button>
      <Table
        columns={columns}
        dataSource={DataList}
        pagination={{
          pageSize: 5,
        }}
      />
      <Modal
        title="添加新闻类型"
        open={isModalOpen}
        onOk={addtitle}
        onCancel={handleCancel}
      >
        <Form ref={addModal}>
          <Form.Item label="类型" name="title">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
